package com.kuang.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: juc
 * @description: 自旋锁
 * @author: 陈恩涛
 * @create: 2021-03-29 14:44
 **/
public class SpinlockDemo {

    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //加锁
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"==> myLock");

        // 第一个线程进来，将原子引用置为线程domo-pool-0,其他线程进来时，自旋等待
        while (!atomicReference.compareAndSet(null, thread)) {

        }
    }

    //解锁
    public void myUnlock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"==> myUnLock");
        atomicReference.compareAndSet(thread,null);
    }
}
